package prosjekt;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.Timer;

/**
 * The logic class used with the {@link KokkPanel KokkPanel} to automatically 
 * update it with new entries from the database.
 * @author Even OEstvold 
 */
public class KokkLogikk{
	/**The time between updates, 30sec*/
	private int updateSpace = 30000;
	/**The panel attached to this logic*/
	private KokkPanel panel;
	/**the timer used to automatic update the product list*/
	private Timer timer;	
	/**
	 * Class constructor for logic between a Database Manager and a KokkPanel.
	 * @param KokkPanel -panel, the KokkPanel to update
	 */
	public KokkLogikk(KokkPanel panel) {
		this.panel = panel;
		//Create the timer with a default time interval of 30 sec.
		timer = new Timer(updateSpace, new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				//look for new/edited products in the database
				getNewUppdates();
			}	
		});
		//Get the first update now
		timer.setInitialDelay(0);
	}
	/**Fetches all the orders that`s not 'don' and updates the panel.*/
	public void getNewUppdates(){
		ResultSet rs = null;
		try {
			panel.removeAllProducts();
			rs = RestaurantDB.getOrders();
			
		} catch (SQLException e) {
			System.err.println(e.getMessage());
		}

		//Konverterer fra database respons til 'Ordre'
		makeOrdre(rs);
	}
	/**
	 * <code>isRunning</code>
	 * <p>
	 * public boolean isRunning()
	 * @return boolean -returns true if the auto update is enabled.
	 */
	public boolean isRunning() {
		return timer.isRunning();
	}
	/**
	 * Starts the automatic update of products to display
	 */
	public void start() {
		timer.start();
	}
	/**
	 * Stops the automatic update of products to display
	 */
	public void stopp(){
		timer.stop();
	}
	/**
	 * Extracts the content from the ResultSet and displays them on the attached
	 * <code>KokkPanel</code> <p>
	 * 
	 * <b>IMPORTANT:</b> the ResultSet must be ordered so that it contains the 
	 * Following fields:
	 * <ol>
	 *	<li>menuNR
	 * 	<li>vareID
	 * 	<li>menNavn
	 * 	<li>kommentar
	 * 	<li>ordreID
	 * </ol>
	 * 
	 * @param rs -ResultSet containing the order information
	 */
	private void makeOrdre(ResultSet rs){
		if (rs == null) return;
		
		try {
			while (rs.next()) {
				int menuNr = rs.getInt(1);
				int vareID = rs.getInt(2);
				String menuNavn = rs.getString(3);
				String komentar = rs.getString(4);
				int ordreID = rs.getInt(5);
				boolean ferdig = rs.getInt(6) == 1;
				if (komentar.isEmpty())
					komentar = "<none>";
	
				panel.addOrdre(ordreID, vareID, menuNr, menuNavn, 
						komentar, ferdig);
			}
		} catch (SQLException e) {
			System.err.println(e.getMessage());
		}
	}
}
